//
//  CaseViewController.m
//  HNJYB
//
//  Created by Mag1cPanda on 16/7/28.
//  Copyright © 2016年 Mag1cPanda. All rights reserved.
//

#import "CaseAuditViewController.h"
#import "CaseDetailViewController.h"
#import "CaseModel.h"
#import "CaseViewController.h"
#import "EdCaseCell.h"
#import "HMSegmentedControl.h"
#import "IngCaseCell.h"
#import "JFCreateProtocolVC.h"
#import "UIScrollView+EmptyDataSet.h"
#import "WaitDutyViewController.h"
#import "XJSGXTViewController.h"
#import "ZRRDViewController.h"
#import "iCarousel.h"
#import "MJRefresh.h"
#import "OneSGSCViewController.h"
#import "XZQXViewController.h"
#import "MNMSGSCViewController.h"
#import "NMNMSGSCViewController.h"
#import "MoreRetakeViewController.h"
#import "OneRetakeViewController.h"
#import "MNMRetakeViewController.h"
#import "NMNMRetakeViewController.h"

@interface CaseViewController ()
< iCarouselDataSource,
iCarouselDelegate,
UITableViewDataSource,
UITableViewDelegate,
DZNEmptyDataSetDelegate,
DZNEmptyDataSetSource >
{
    UITableView *ingTable;
    UITableView *edTable;
    NSMutableArray *ingArr;
    NSMutableArray *edArr;
    
    NSMutableDictionary *ingBean;
    NSMutableDictionary *edBean;
    NSInteger ingPage;
    NSInteger edPage;
    NSString *ingTotalCount;
    NSString *edTotalCount;

    MBProgressHUD *hud;
}
@property (nonatomic, strong) HMSegmentedControl *segmentControl;
@property (nonatomic, strong) iCarousel *carousel;
@end

@implementation CaseViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"历史案件";
    ingArr = [NSMutableArray array];
    edArr = [NSMutableArray array];
    ingBean = [NSMutableDictionary dictionary];
    edBean = [NSMutableDictionary dictionary];
    [ingBean setValue:GlobleInstance.userflag forKey:@"username"];
    [ingBean setValue:GlobleInstance.token forKey:@"token"];
    [ingBean setValue:@"10" forKey:@"pagesize"];
    [ingBean setValue:@"1" forKey:@"pagenum"];
    
    [edBean setValue:GlobleInstance.userflag forKey:@"username"];
    [edBean setValue:GlobleInstance.token forKey:@"token"];
    [edBean setValue:@"10" forKey:@"pagesize"];
    [edBean setValue:@"1" forKey:@"pagenum"];
    ingPage = 1;
    edPage = 1;

    [self initSegmentControlAndCarousel];

    [self initTableView];

    hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [self loadIngData];
    [self loadEdData];
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark - 初始化segmentControl和Carousel
- (void)initSegmentControlAndCarousel
{
    _carousel = [[iCarousel alloc]
        initWithFrame:CGRectMake(0, 40, ScreenWidth, ScreenHeight - 104)];
    _carousel.dataSource = self;
    _carousel.delegate = self;
    _carousel.decelerationRate = 0.7;
    _carousel.type = iCarouselTypeLinear;
    _carousel.pagingEnabled = YES;
    _carousel.edgeRecognition = YES;
    _carousel.bounces = NO;
    [self.view addSubview:_carousel];

    _segmentControl = [[HMSegmentedControl alloc]
        initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    _segmentControl.sectionTitles = @[ @"处理中", @"已完成" ];
    _segmentControl.backgroundColor = HNBackColor;
    _segmentControl.titleTextAttributes =
        @{NSFontAttributeName : [UIFont systemFontOfSize:15]};
    _segmentControl.selectedTitleTextAttributes = @{
        NSForegroundColorAttributeName : HNBlue,
        NSFontAttributeName : [UIFont systemFontOfSize:16]
    };
    _segmentControl.selectionIndicatorColor = HNBlue;
    _segmentControl.selectionStyle =
        HMSegmentedControlSelectionStyleFullWidthStripe;
    _segmentControl.selectionIndicatorLocation =
        HMSegmentedControlSelectionIndicatorLocationDown;
    _segmentControl.selectionIndicatorHeight = 2.0;
    [self.view addSubview:_segmentControl];

    __weak typeof(self) weakSelf = self;

    [self.segmentControl setIndexChangeBlock:^(NSInteger index) {

      [weakSelf.carousel scrollToItemAtIndex:index animated:NO];

    }];
}

#pragma mark - 初始化tableView
- (void)initTableView
{
    ingTable = [[UITableView alloc] initWithFrame:_carousel.bounds
                                            style:UITableViewStylePlain];
    ingTable.delegate = self;
    ingTable.dataSource = self;
    ingTable.emptyDataSetDelegate = self;
    ingTable.emptyDataSetSource = self;
    ingTable.hidden = YES;
    ingTable.tableFooterView = [UIView new];
    ingTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(ingRefreshData)];
    
    ingTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(ingLoadMoreData)];
    [ingTable.mj_footer setAutomaticallyHidden:YES];

    edTable = [[UITableView alloc] initWithFrame:_carousel.bounds
                                           style:UITableViewStylePlain];
    edTable.delegate = self;
    edTable.dataSource = self;
    edTable.emptyDataSetDelegate = self;
    edTable.emptyDataSetSource = self;
    edTable.hidden = YES;
    edTable.tableFooterView = [UIView new];
    edTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(edRefreshData)];
    
    edTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(edLoadMoreData)];
    [edTable.mj_footer setAutomaticallyHidden:YES];
}

#pragma mark - 加载数据
-(void)loadIngData
{
    [LSHttpManager requestUrl:HNServiceURL
                  serviceName:@"kckpjjappSearchAllUndoCase"
                   parameters:ingBean
                     complete:^(id result, ResultType resultType) {
                         
                         if (result)
                         {
                             NSLog(@"kckpjjappSearchAllUndoCase -> %@", JsonResult);
                             ingTable.hidden = NO;
                         }
                         
                         if (![hud isHidden]) {
                             [hud hideAnimated:YES];
                         }
                         
                         if ([result[@"restate"] isEqualToString:@"1"])
                         {
                             if ([result[@"data"][@"insure"] isKindOfClass:[NSArray class]])
                             {
                                 NSArray *data = result[@"data"][@"insure"];
                                 for (NSDictionary *dic in data)
                                 {
                                     CaseModel *model =
                                     [[CaseModel alloc] initWithDict:dic];
                                     [ingArr addObject:model];
                                 }
                             }
                         }
                         [ingTable reloadData];
                     }];
}

-(void)loadEdData
{
    [LSHttpManager requestUrl:HNServiceURL
                  serviceName:@"kckpjjappSearchAllCase"
                   parameters:edBean
                     complete:^(id result, ResultType resultType) {
                         
                         if (result)
                         {
                             NSLog(@"kckpjjappSearchAllCase -> %@", JsonResult);
                             edTable.hidden = NO;
                         }
                         
                         if (![hud isHidden]) {
                             [hud hideAnimated:YES];
                         }
                         
                         if ([result[@"restate"] isEqualToString:@"1"])
                         {
                             if ([result[@"data"][@"incure"] isKindOfClass:[NSArray class]])
                             {
                                 NSArray *data = result[@"data"][@"incure"];
                                 for (NSDictionary *dic in data)
                                 {
                                     CaseModel *model =
                                     [[CaseModel alloc] initWithDict:dic];
                                     [edArr addObject:model];
                                     
                                 }
                                 
                             }
                         }
                         [edTable reloadData];
                     }];
}

-(void)ingRefreshData
{
    ingPage = 1;
    [ingArr removeAllObjects];
    
    [ingTable.mj_header endRefreshing];
    [ingTable.mj_footer setState:1];
    
    [ingBean setValue:@"1" forKey:@"pagenum"];
    
    [self loadIngData];
}

-(void)ingLoadMoreData
{
    ingPage++;
    
    [ingBean setValue:[NSString stringWithFormat:@"%zi",ingPage] forKey:@"pagenum"];
    
    [LSHttpManager requestUrl:HNServiceURL
                  serviceName:@"kckpjjappSearchAllUndoCase"
                   parameters:ingBean
                     complete:^(id result, ResultType resultType) {
        
        //        NSLog(@"csitopnews ~ %@",result);
        NSLog(@"kckpjjappSearchAllUndoCase ~ %@",[Util objectToJson:result]);
        
        if ([result[@"restate"] isEqualToString:@"1"]) {
            
            ingTotalCount = result[@"data"][@"num"];
            
            id tmpObj = result[@"data"][@"insure"];
            
            if ([tmpObj isKindOfClass:[NSArray class]]) {
                NSArray *arr = tmpObj;
                for (NSDictionary *dic in arr) {
                    CaseModel *model = [[CaseModel alloc] initWithDict:dic];
                    [ingArr addObject:model];
                }
            }
            
            if (ingArr.count == [ingTotalCount integerValue]) {
                [ingTable.mj_footer endRefreshingWithNoMoreData];
            }
            
            else {
                [ingTable.mj_footer endRefreshing];
            }
            
            [ingTable reloadData];
        }
    }];
}

-(void)edRefreshData
{
    edPage = 1;
    [edArr removeAllObjects];
    
    [edTable.mj_header endRefreshing];
    [edTable.mj_footer setState:1];
    
    [edBean setValue:@"1" forKey:@"pagenum"];
    
    [self loadEdData];
}

-(void)edLoadMoreData
{
    edPage++;
    
    [edBean setValue:[NSString stringWithFormat:@"%zi",edPage] forKey:@"pagenum"];
    
    [LSHttpManager requestUrl:HNServiceURL
                  serviceName:@"kckpjjappSearchAllCase"
                   parameters:edBean
                     complete:^(id result, ResultType resultType) {
        
        //        NSLog(@"csitopnews ~ %@",result);
        NSLog(@"kckpjjappSearchAllCase ~ %@",[Util objectToJson:result]);
        
        if ([result[@"restate"] isEqualToString:@"1"]) {
            
            edTotalCount = result[@"data"][@"num"];
            
            id tmpObj = result[@"data"][@"incure"];
            
            if ([tmpObj isKindOfClass:[NSArray class]]) {
                NSArray *arr = tmpObj;
                for (NSDictionary *dic in arr) {
                    CaseModel *model = [[CaseModel alloc] initWithDict:dic];
                    [edArr addObject:model];
                }
            }
            
            if (edArr.count == [edTotalCount integerValue])  {
                [edTable.mj_footer endRefreshingWithNoMoreData];
            }
            
            else {
                [edTable.mj_footer endRefreshing];
            }
            
            [edTable reloadData];
        }
    }];
}


#pragma mark - iCarousel的代理方法
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    return 2;
}

- (UIView *)carousel:(iCarousel *)carousel
  viewForItemAtIndex:(NSUInteger)index
         reusingView:(UIView *)view
{
    if (index == 0)
    {
        view = ingTable;
    }
    else
    {
        view = edTable;
    }

    return view;
}

- (void)carouselCurrentItemIndexDidChange:(iCarousel *)carousel
{
    [_segmentControl setSelectedSegmentIndex:carousel.currentItemIndex
                                    animated:YES];
}

#pragma mark - 继续处理
- (void)continueProcessing:(UIButton *)btn
{
    CaseModel *model = ingArr[btn.tag];
    //给单例appcaseno重新赋值
    GlobleInstance.appcaseno = model.appcaseno;

    //案件信息
    if ([model.state isEqualToString:@"9"])
    {
        //单车
        if ([model.casetype isEqualToString:@"0"])
        {
            OneSGSCViewController *vc = [OneSGSCViewController new];
            vc.isHistoryPush = YES;
            GlobleInstance.caseType = HNCaseTypeOneCar;
            [self.navigationController pushViewController:vc animated:YES];
        }
        //双车
        if ([model.casetype isEqualToString:@"1"])
        {
            GlobleInstance.caseType = HNCaseTypeMoreCar;
            
            //交警
            if (GlobleInstance.userType == TrafficPolice)
            {
                XZQXViewController *vc = [XZQXViewController new];
                vc.isHistoryPush = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
            //协警
            else
            {
                XJSGXTViewController *vc = [XJSGXTViewController new];
                vc.isHistoryPush = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
        //机动车与非机动车
        if ([model.casetype isEqualToString:@"10"]) {
            MNMSGSCViewController *vc = [MNMSGSCViewController new];
            vc.isHistoryPush = YES;
            GlobleInstance.caseType = HNCaseTypeMNM;
            [self.navigationController pushViewController:vc animated:YES];
        }
        //非机动车与非机动车
        if ([model.casetype isEqualToString:@"11"]) {
            NMNMSGSCViewController *vc = [NMNMSGSCViewController new];
            vc.isHistoryPush = YES;
            GlobleInstance.caseType = HNCaseTypeNMNM;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
    //生成协议
    else if ([model.state isEqualToString:@"10"])
    {
        JFCreateProtocolVC *vc = [JFCreateProtocolVC new];
        vc.casenumber = model.casenumber;
        vc.isHistoryPush = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }

    //等待定责
    else if ([model.state isEqualToString:@"1"])
    {
        WaitDutyViewController *vc = [WaitDutyViewController new];
        GlobleInstance.appcaseno = model.appcaseno;
        [self.navigationController pushViewController:vc animated:YES];
    }

    //定责照片待审
    else if ([model.state isEqualToString:@"7"])
    {
        CaseAuditViewController *vc = [CaseAuditViewController new];
        GlobleInstance.appcaseno = model.appcaseno;
        [self.navigationController pushViewController:vc animated:YES];
    }

    //撤销案件
    else if ([model.state isEqualToString:@"6"])
    {
        MBProgressHUD *cxHud =
            [MBProgressHUD showHUDAddedTo:self.view animated:false];
        cxHud.mode = MBProgressHUDModeText;
        cxHud.label.text = @"案件已撤销";
        cxHud.label.font = HNFont(13);
        [cxHud hideAnimated:YES afterDelay:1.5];
    }
    
    //重拍
    else if ([model.state isEqualToString:@"14"])
    {
        //单车
        if ([model.casetype isEqualToString:@"0"])
        {
            OneRetakeViewController *vc = [OneRetakeViewController new];
            vc.isHistoryPush = YES;
            GlobleInstance.caseType = HNCaseTypeOneCar;
            [self.navigationController pushViewController:vc animated:YES];
        }
        //双车
        if ([model.casetype isEqualToString:@"1"])
        {
            MoreRetakeViewController *vc = [MoreRetakeViewController new];
            vc.isHistoryPush = YES;
            GlobleInstance.caseType = HNCaseTypeMoreCar;
            [self.navigationController pushViewController:vc animated:YES];
        }
        //机动车与非机动车
        if ([model.casetype isEqualToString:@"10"])
        {
            MNMRetakeViewController *vc = [MNMRetakeViewController new];
            vc.isHistoryPush = YES;
            GlobleInstance.caseType = HNCaseTypeMNM;
            [self.navigationController pushViewController:vc animated:YES];
        }
        //非机动车与非机动车
        if ([model.casetype isEqualToString:@"11"])
        {
            NMNMRetakeViewController *vc = [NMNMRetakeViewController new];
            vc.isHistoryPush = YES;
            GlobleInstance.caseType = HNCaseTypeNMNM;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

#pragma mark - tableView Delegate & DataSource
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    if (tableView == ingTable)
    {
        return ingArr.count;
    }

    else
    {
        return edArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == ingTable)
    {
        NSString *cellId =
            [NSString stringWithFormat:@"IngCaseCell%zi", indexPath.row];

        [ingTable registerNib:[UINib nibWithNibName:@"IngCaseCell" bundle:nil]
            forCellReuseIdentifier:cellId];

        IngCaseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.jxclBtn.tag = indexPath.row;
        [cell.jxclBtn addTarget:self
                         action:@selector(continueProcessing:)
               forControlEvents:1 << 6];

        if (ingArr.count > indexPath.row)
        {
            CaseModel *model = ingArr[indexPath.row];
            cell.model = model;
        }

        return cell;
    }

    else
    {
        NSString *cellId =
        [NSString stringWithFormat:@"EdCaseCell%zi", indexPath.row];
        
        [edTable registerNib:[UINib nibWithNibName:@"EdCaseCell" bundle:nil]
       forCellReuseIdentifier:cellId];
        
        EdCaseCell *cell =
            [tableView dequeueReusableCellWithIdentifier:cellId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        if (edArr.count > indexPath.row)
        {
            CaseModel *model = edArr[indexPath.row];
            cell.model = model;
        }

        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView
    heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == ingTable)
    {
        return 120;
    }

    else
    {
        return 80;
    }
}

- (void)tableView:(UITableView *)tableView
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CaseModel *model;
    if (tableView == ingTable)
    {
        model = ingArr[indexPath.row];
    }

    else
    {
        model = edArr[indexPath.row];
    }

    if ([model.state isEqualToString:@"9"] ||
        [model.state isEqualToString:@"7"] ||
        [model.state isEqualToString:@"14"])
    {
        MBProgressHUD *noHud = [MBProgressHUD showHUDAddedTo:self.view animated:NO];
        noHud.mode = MBProgressHUDModeText;
        noHud.label.text = @"该案件暂无办理详情";
        [noHud hideAnimated:YES afterDelay:1];
    }

    else
    {
        CaseDetailViewController *vc = [CaseDetailViewController new];
        vc.casenumber = model.casenumber;
        vc.caseState = model.state;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - DZNEmptyDataSetDelegate Methods
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
{
    UIView *backView = [[UIView alloc] initWithFrame:scrollView.bounds];
    UIImageView *imageV =
        [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 317, 280)];
    imageV.center = scrollView.center;
    imageV.image = [UIImage imageNamed:@"unfinished"];
    [backView addSubview:imageV];
    return backView;
}

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
{
    return YES;
}

@end
